<template>
	<div class="list">
		<a-form ref="searchFormRef" class="search-form base-mb15" :label-col="{ style: { minWidth: '100px' } }"
			:model="searchFormState" @finish="onSearchFinish">
			<a-row :gutter="[10, 24]">
				<a-col :span="6">
					<a-form-item name="orgId" :label="$t('self.order.tips201')">
						<a-select v-model:value="searchFormState.orgId" :options="searchOrgOptions"
							:fieldNames="{label: 'orgName',value: 'id'}" @change="handleOrgChange"
							:placeholder="$t('self.pleaseChoose')" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item name="stationId" :label="$t('self.order.tips6')">
						<a-select v-model:value="searchFormState.stationId" :options="stationOptions"
							@change="handleStationNameChange" :fieldNames="{label: 'stationName',value: 'id'}"
							:placeholder="$t('self.pleaseChoose')" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item name="pileSeri" :label="$t('self.order.tips181')">
						<a-select v-model:value="searchFormState.pileSeri" :options="pileOptions"
							:fieldNames="{label: 'pileSeri',value: 'id'}" :placeholder="$t('self.pleaseChoose')" />
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="[10,24]" class="base-mt20">
				<a-col :span="4">
					<a-radio-group @change="onDateModeChange" v-model:value="dateMode" size="small"
						style="display: flex;flex-direction: row;">
						<a-radio-button value="month" style="width: 70px;height: 35px;line-height: 35px;display: 
						flex;justify-content: center;align-items: center;">{{ $t('self.index.tips2') }}</a-radio-button>
						<a-radio-button value="day" style="width: 70px;height: 35px;line-height: 35px;display: 
						flex;justify-content: center;align-items: center;">{{ $t('self.index.tips4') }}</a-radio-button>
					</a-radio-group>
				</a-col>

				<a-col :span="7">
					<a-form-item name="startTime" :label="$t('self.order.tips14')"
						:label-col="{ style: { minWidth: '70px' } }">
						<a-date-picker v-if="dateMode === 'day'" v-model:value="searchFormState.startTime"
							style="width: 100%" />
						<a-month-picker v-else v-model:value="searchFormState.startTime"
							:disabled="dateMode === 'month'" style="width: 100%" />
					</a-form-item>
				</a-col>

				<a-col :span="7">
					<a-form-item name="endTime" :label="$t('self.order.tips15')"
						:label-col="{ style: { minWidth: '70px' } }">
						<a-date-picker v-if="dateMode === 'day'" v-model:value="searchFormState.endTime"
							style="width: 100%" />
						<a-month-picker v-else v-model:value="searchFormState.endTime" :disabled="dateMode === 'month'"
							style="width: 100%" />
					</a-form-item>
				</a-col>

				<a-col :span="4" offset="1" class="base-flex base-rows">
					<a-button type="primary" html-type="submit">{{ $t('self.searchButton') }}</a-button>
					<a-button class="base-ml10" @click="resetSearchForm">{{ $t('self.resetButton') }}</a-button>
				</a-col>
			</a-row>

		</a-form>
		<s-table ref="stableRef" :api-obj="tableConfig.apiObj" api-method="POST" :columns="sourceColumn" row-key="id"
			:light-index="tableConfig.lightIndex" :is-row-selection="false" @selectionChange="tableSelectionChange"
			:is-show-tool="false">
			<!-- 		<s-table 
			ref="stableRef"  
			:data="tableData" 
			:columns="sourceColumn" 
			row-key="id"
			:light-index="tableConfig.lightIndex" 
			:is-row-selection="false" 
			@selectionChange="tableSelectionChange"
			:is-show-tool="false" :scroll="{ x: 1400 }"> -->
			<template #bodyCell="{ column, record, index }"></template>
		</s-table>
	</div>
</template>

<script setup>
	import {
		getCurrentInstance,
		nextTick,
		onMounted,
		ref,
		watch
	} from 'vue'

	import {
		useRoute,
		useRouter
	} from 'vue-router'
	import ScStatusIndicator from '@/components/scMini/scStatusIndicator.vue'
	import {
		mainStore
	} from '@/stores/mainStore'
	import dayjs from 'dayjs'
	import {
		message
	} from 'ant-design-vue'
	const {
		proxy
	} = getCurrentInstance()
	const $TOOL = proxy.$TOOL
	const $API = proxy.$API
	const $T = proxy.$t
	const route = useRoute()
	const router = useRouter()
	const useMainStore = mainStore()

	const dateMode = ref('month') // 默认按月
	const open = ref(false)
	const apiParams = ref({});
	const selectedKey = ref([])
	const stableRef = ref(null)
	// const tableConfig = ref({
	// 	pagination: {
	// 		total: 30,
	// 		current: 1,
	// 		pageSize: 10
	// 	},
	// 	apiObj: null,
	// 	lightIndex: []
	// })
	const tableConfig = ref({
		apiObj: $API.backend.report.stationReport,
		loading: true,
		lightIndex: [] // 要高亮的行号
	})
	const sourceColumn = ref([])
	const tableData = ref([])
	const stationOptions = ref([])
	//获取当前登录用户的所属运营商
	const formState = ref({
		"id": $TOOL.data.get('USERID'),
		"step": 1,
		"orgIds": [],
		"chargeStationIds": []
	})
	onMounted(async () => {
		resetDefaultOptionsByLang()
		getUserOrgRole()
		const defaultFmt = dateMode.value === 'month' ? 'YYYY-MM' : 'YYYY-MM-DD'
		apiParams.value = {
			orgId: '',
			stationId: '',
			pileSeri: '',
			startTime: dayjs().subtract(1, 'month').format(defaultFmt), // 近一月
			endTime: dayjs().format(defaultFmt),
			type: dateMode.value === 'month' ? 1 : 2,
		}
	})
	const onDateModeChange = () => {
		// 1 => 按月  2 => 按日
		searchFormState.value.type = dateMode.value === 'month' ? 1 : 2
	}
	//运营商筛选
	const getUserOrgRole = () => {
		$API.backend.systemUser.queryUserOrgRole.post({
			id: formState.value.id
		}).then(res => {
			const {
				objData
			} = res
			searchOrgOptions.value = objData.orgList
		}).catch(err => {
			message.error(err.msg);
		})
	}
	//站点筛选
	const handleOrgChange = async (orgId) => {
		// 清空历史
		searchFormState.stationId = null
		stationOptions.value = []

		if (!orgId) return
		try {
			const res = await $API.backend.businessStation.queryStationListByOrgIds.post({
				orgIds: orgId
			})
			if (res.code === 200) {
				formState.value.orgIds = orgId
				stationOptions.value = res.objData ?? []
			}
		} catch (err) {
			message.error(err.msg);
		}
	}
	const handleStationNameChange = async (id) => {
		searchFormState.value.stationId = id
	}
	const getStationReport = async (params = {}) => {
		const clean = {
			orgId: params.orgId || undefined,
			stationId: params.stationId || undefined,
			pileSeri: params.pileSeri || undefined,
			startTime: params.startTime || undefined,
			endTime: params.endTime || undefined,
			type: params.type ?? 1,
			pageNo: params.pageNo ?? 1,
			pageSize: params.pageSize ?? 10,
		}

		try {
			const res = await $API.backend.report.stationReport.post(clean)
			if (!res.data || res.data.length === 0) {
				tableData.value = [];
				return;
			}
			console.log("res.data=====",res.data)
			tableData.value = res.data
		} catch (error) {
			// const res = await $API.backend.report.stationReport.post(clean)
			// tableData.value = res.data
			console.error("接口异常：", error)
			if (!error.data || error.data.length === 0) {
				tableData.value = [];
				return;
			}
			tableData.value = error.data
			// message.error($T('self.message.loadFailed'))
			message.error(err.msg);
		}
	}
	const resetDefaultOptionsByLang = () => {
		sourceColumn.value = [{
				title: $T('self.operators.tips1'),
				dataIndex: 'orgName',
				key: 'orgName'
			},
			// {
			// 	title: $T('self.order.tips6'),
			// 	dataIndex: 'stationName',
			// 	key: 'stationName'
			// },

			{
				title: $T('self.order.tips222'),
				dataIndex: 'totalChargeQuantity',
				key: 'totalChargeQuantity',
				customRender: ({text, record}) => {
					const numericValue = parseFloat(text);
					if (isNaN(numericValue)) return '';
					return (numericValue / 1000).toFixed(2);
				},
			},
			{
				title: $T('self.order.tips11'),
				dataIndex: 'totalAmount',
				key: 'totalAmount'
			},
			{
				title: $T('self.stationMap.tips2'),
				dataIndex: 'totalChargeNum',
				key: 'totalChargeNum'
			},
			{
				title: $T('self.order.tips10'),
				dataIndex: 'totalChargeTimes',
				key: 'totalChargeTimes',
				// 自定义显示列
				// customRender: ({
				// 	text,
				// 	record
				// }) => {
				// 	// 接口返回是秒，处理为分
				// 	return proxy.getMinBySeconds(text)
				// },
			},
			{
				title: $T('self.statisticalTime'),
				dataIndex: 'createTime',
				key: 'createTime'
			},
		]
	}

	const tableSelectionChange = (rows, record) => {
		selectedKey.value = rows
	}

	const searchFormRef = ref(null)

	const searchFormState = ref({
		orgId: '',
		stationId: '',
		pileSeri: '',
		startTime: null,
		endTime: null,
		type: 1,
		pageNo: 1,
		pageSize: 10,
	})

	const searchOrgOptions = ref([])
	const searchOrderTypeOptions = ref([])
	const searchStatusOptions = ref([])
	const onSearchFinish = () => {
		console.log(searchFormState.value)
		const {
			orgId,
			stationId,
			pileSeri,
			startTime,
			endTime,
			type
		} = searchFormState.value
		const fmt = type === 1 ? 'YYYY-MM' : 'YYYY-MM-DD'

		const clean = {
			orgId,
			stationId,
			pileSeri,
			startTime: startTime ? dayjs(startTime).format(fmt) : '',
			endTime: endTime ? dayjs(endTime).format(fmt) : '',
			type,
			pageNo: 1,
			pageSize: 10,
		}
		stableRef.value?.reload?.(clean);
		// getStationReport(clean)
	}

	const resetSearchForm = () => {
		searchFormRef.value.resetFields()
		dateMode.value = 'month'
		searchFormState.value.type = 1
		searchFormState.value.pageNo = 1
		searchFormState.value.pageSize = 10

		const defaultFmt = 'YYYY-MM'
		apiParams.value = {
			orgId: '',
			stationId: '',
			pileSeri: '',
			startTime: dayjs().subtract(1, 'month').format(defaultFmt),
			endTime: dayjs().format(defaultFmt),
			type: 1,
			pageNo: 1,
			pageSize: 10,
		}
	}
	watch(
		() => searchFormState.value.dateValue,
		(val) => {
			if (!val) return
			const fmt = dateMode.value === 'month' ? 'YYYY-MM' : 'YYYY-MM-DD'
			console.log('当前选中：', dayjs(val).format(fmt))
		},
		() => useMainStore.lang,
		(curr, old) => {
			resetDefaultOptionsByLang()
		}
	)
</script>

<style lang="scss" scoped>
	.mode-row {
		margin-bottom: 8px;
	}

	.list {
		height: 100%;
		background: #ffffff;
		padding: 15px;

		.search-form {
			padding: 16px;
			background: rgb(247, 248, 250);

			:deep(.ant-form-item) {
				margin-bottom: 0;
			}
		}
	}
</style>